<?php

namespace App\Filament\Pages\Permission;

use App\Enums\NavigationGroup;
use App\Models\Admin\AdminPermission;
use Filament\Actions\Action;
use Filament\Actions\Concerns\InteractsWithActions;
use Filament\Actions\Contracts\HasActions;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Forms\Contracts\HasForms;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Support\Facades\FilamentView;
use Filament\View\PanelsRenderHook;
use Illuminate\Validation\Rule;

class Permission extends Page implements HasActions, HasForms
{
    use InteractsWithActions;
    use InteractsWithForms;

    public static string|null|\UnitEnum $navigationGroup = NavigationGroup::Permissions;

    public static ?string $navigationLabel = '权限列表';

    protected static ?int $navigationSort = 30;

    protected static ?string $modelLabel = '权限标识';

    protected string $view = 'filament.pages.permission';

    public static function shouldRegisterNavigation(): bool
    {
        return auth()->user()->can('admin.permission.list');
    }

    public function boot(): void
    {
        FilamentView::registerRenderHook(
            PanelsRenderHook::CONTENT_BEFORE,
            function () {
                return view('components.resources.list-header', [
                    'title' => '权限列表',
                    'description' => '新增、编辑、删除后台管理员权限',
                ]);
            }
        );
    }

    public function getTitle(): string
    {
        return '';
    }

    public function editAction(): Action
    {
        return Action::make('edit')
            ->label('编辑')
            ->modal()
            ->fillForm(function ($arguments) {
                $permission = AdminPermission::find($arguments['id']);

                return [
                    'id' => $permission->id,
                    'name' => $permission->name,
                    'title' => $permission->title,
                    'parent_id' => $permission->parent_id,
                ];
            })
            ->visible(fn () => auth()->user()->can('admin.permission.edit'))
            ->schema([
                Select::make('parent_id')
                    ->label('上级权限')
                    ->native(false)
                    ->options($this->getSelectOptions()),
                TextInput::make('title')
                    ->label('权限名称')
                    ->placeholder('请输入权限名称')
                    ->maxLength(20)
                    ->required(),
                TextInput::make('name')
                    ->label('权限标识')
                    ->placeholder('请输入权限标识')
                    ->required()
                    ->rule(function (callable $get) {
                        $id = $get('id');

                        return Rule::unique(AdminPermission::class, 'name')->ignore($id);
                    }),
            ])
            ->action(function (array $data, $arguments): void {
                $data['parent_id'] = $data['parent_id'] ?? 0;
                $permission = AdminPermission::find($arguments['id']);
                if ($permission) {
                    $permission->update($data);
                }
            })
            ->successNotificationTitle('权限更新成功');
    }

    public function deleteAction(): Action
    {
        return Action::make('delete')
            ->label('删除')
            ->requiresConfirmation()
            ->visible(fn () => auth()->user()->can('admin.permission.delete'))
            ->action(function ($arguments): void {
                $record = AdminPermission::find($arguments['id']);
                if ($record) {
                    // 检查是否有子权限，如果有则不能删除
                    if ($record->children()->exists()) {
                        Notification::make()->title('无法删除')
                            ->body('该权限下有子权限，请先删除子权限')
                            ->danger()
                            ->send();

                        return;
                    }

                    $record->delete();
                    $record->roles()->detach();

                    Notification::make()
                        ->title('删除成功')
                        ->success()
                        ->send();
                }
            });
    }

    public function createAction(): Action
    {
        return Action::make('create')
            ->label('新增权限')
            ->modal()
            ->schema([
                Select::make('parent_id')
                    ->label('上级权限')
                    ->native(false)
                    ->options($this->getSelectOptions()),
                TextInput::make('title')
                    ->label('权限名称')
                    ->placeholder('请输入权限名称')
                    ->maxLength(20)
                    ->required(),
                TextInput::make('name')
                    ->label('权限标识')
                    ->placeholder('请输入权限标识')
                    ->required()
                    ->unique(AdminPermission::class),
            ])
            ->visible(fn () => auth()->user()->can('admin.permission.add'))
            ->action(function (array $data): void {
                $data['guard_name'] = 'admin';
                $data['parent_id'] = $data['parent_id'] ?? 0;
                AdminPermission::create($data);
            })
            ->successNotificationTitle('权限创建成功');
    }

    public function getViewData(): array
    {
        $permissions = AdminPermission::with('children')
            ->where('parent_id', 0)
            ->get();

        $columns = [
            ['name' => 'title', 'label' => '权限名称', 'class' => 'col-span-4'],
            ['name' => 'name', 'label' => '权限标识', 'class' => 'col-span-4'],
            ['name' => 'created_at', 'label' => '创建时间', 'class' => 'col-span-4'],
        ];

        return [
            'items' => $permissions,
            'columns' => $columns,
        ];
    }

    protected function getSelectOptions(): array
    {
        $topPermissions = AdminPermission::where('parent_id', 0)
            ->with('children')
            ->get();

        $options = ['0' => '顶级权限'];
        foreach ($topPermissions as $permission) {
            $options[$permission->id] = $permission->title;

            $children = $permission->children;
            foreach ($children as $child) {
                $options[$child->id] = '└─ '.$child->title;
            }
        }

        return $options;
    }
}
